package com.hbnu.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author kittychen
 * @since 2025-10-22 8:58
 */
public class JdbcDemo04 {

    public static void main(String[] args) {
        // 1、模拟前端（提供界面，用户输入账号和密码）
        Map<String, String> userInfo = initUI();

        // 2、模拟后端（接收前端收据，并进行数据处理，并将处理结果返回给前端）
        boolean result = checkUserInfo(userInfo);

        System.out.println(result ? "登录成功" : "登录失败");
    }

    private static boolean checkUserInfo(Map<String, String> userInfo) {
        boolean flag = false;

        String name = userInfo.get("username");
        String pwd = userInfo.get("password");

        Connection connection = null;
        // Statement statement = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2.获取数据库连接
            String url = "jdbc:mysql://localhost:3306/class2310?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String user = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, user, password);

            // 3、获取数据库操作对象
            // statement = connection.createStatement();

            // 4、执行SQL语句
            // String sql = "select * from tb_user where username='" + name + "' and password='" + pwd + "'";
            String sql = "select * from tb_user where username = ? and password = ?";  // ? 占位符
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, pwd);
            // resultSet = statement.executeQuery(sql);
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                flag = true;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    private static Map<String, String> initUI() {
        Map<String, String> userInfo = new HashMap<>();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的用户名：");
        String username = scanner.nextLine();
        System.out.println("请输入您的密码：");
        String password = scanner.nextLine();

        userInfo.put("username", username);
        userInfo.put("password", password);

        return userInfo;
    }
}
